package saleMarket.controller.authority;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import saleMarket.domain.User;
import saleMarket.domain.authority.Actor;
import saleMarket.domain.authority.ActorAssRole;
import saleMarket.domain.authority.Role;
import saleMarket.service.UserService;
import saleMarket.service.authority.ActorAssRoleService;
import util.JSONUtil;
import util.TokenHelper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.TreeSet;

@WebServlet("/login.ctl")
public class LoginController extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //将request body转换为JSON字串
        String user_json = JSONUtil.getJSON(request);
        //将JSON字串解析为User对象
        User userToLogin = JSON.parseObject(user_json, User.class);
        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();
        try {
            //根据user对象获取actor对象
            Actor currentActor = UserService.getInstance().
                    login(userToLogin);
            System.out.println(currentActor);
            //没有获取到actor对象则向前端相应:用户名或密码不匹配
            if (currentActor == null) {
                message.put("message", "用户名或密码不匹配");
                response.getWriter().println(message);
                return;
            } else {
                String token = TokenHelper.getToken(currentActor.getName());
                request.getSession().setAttribute("token",token);
                //获得某Actor对象关联的ActorAssRole对象
                ActorAssRole actorAssRoleCollection =
                        ActorAssRoleService.getInstance().find(currentActor.getId());
                //根据ActorAssRole对象获得对应的Role对象
                Role role = actorAssRoleCollection.getRole();

                message.put("actor", currentActor);
                message.put("roles", role.getDescription());
            }
        } catch (SQLException e) {
            message.put("message", "数据库操作异常");
            //响应message到前端
            e.printStackTrace();
        } catch (Exception e) {
            message.put("message", "网络异常");
            e.printStackTrace();
            //响应message到前端
        }
        response.getWriter().println(message);
    }

}
